package com.swak.codec.checksum;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.zip.Checksum;

/**
 * Java9Crc32C.
 * 
 * @author 618lf
 */
public class Java9Crc32C implements Checksum {

	private static final MethodHandle NEW_CRC32C_MH;

	static {
		MethodHandle newCRC32C = null;
		try {
			newCRC32C = MethodHandles.publicLookup().findConstructor(Class.forName("java.util.zip.CRC32C"),
					MethodType.methodType(void.class));
		} catch (ReflectiveOperationException e) {
			// Should not reach here.
			throw new RuntimeException(e);
		}
		NEW_CRC32C_MH = newCRC32C;
	}
	private Checksum checksum;

	public Java9Crc32C() {
		try {
			this.checksum = (Checksum) NEW_CRC32C_MH.invoke();
		} catch (Throwable e) {
		}
	}

	@Override
	public void update(int b) {
		checksum.update(b);
	}

	@Override
	public void update(byte[] b, int off, int len) {
		checksum.update(b, off, len);
	}

	@Override
	public long getValue() {
		return checksum.getValue();
	}

	@Override
	public void reset() {
		checksum.reset();
	}
}
